package com.jade.store.wechat.service.impl;

import com.jade.bss.base.customer.Customer;
import com.jade.bss.db.impl.BaseFacadeImpl;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.store.wechat.biz.business.user.UserGetBusiness;
import com.jade.store.wechat.biz.business.user.UserInfoBatchetBusiness;
import com.jade.store.wechat.biz.business.user.UserInfoBusiness;
import com.jade.store.wechat.biz.protocol.user.*;
import com.jade.store.wechat.biz.protocol.user.userTool.UserBatchGetReqTool;
import com.jade.store.wechat.dao.WechatUserDao;
import com.jade.store.wechat.entity.WechatUser;
import com.jade.store.wechat.service.WechatUserFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: JinYa 2009_jinya@163.com
 * Date: 2016-5-5
 * Time: 10:53
 * Version : 1.0
 * Remark:
 * History:
 */
@Service("WechatUserFacade")
public class WechatUserFacadeImpl extends BaseFacadeImpl implements WechatUserFacade {
    @Inject
    @Named("WechatUserDao")
    private WechatUserDao wechatUserDao;
    /**
     * 同步微信用户
     * @param appid
     * @param appid
     * @throws Exception
     */

    public WechatUser  getWxUser(String appid,String openId)  throws  Exception{
        UserInfoBusiness _business=new UserInfoBusiness(appid);
        UserInfoReq req=new UserInfoReq();
        req.setOpenid(openId);
        WechatUser wechatUser=new WechatUser();
        UserInfoRes userInfoRes=_business.run(req);
        wechatUser.setAppId(appid);
        wechatUser.setSubscribe(userInfoRes.getSubscribe());
        wechatUser.setOpenid(userInfoRes.getOpenid());
        wechatUser.setNickname(escapeExprSpecialWord(userInfoRes.getNickname()));
        wechatUser.setSex(userInfoRes.getSex());
        wechatUser.setCity(userInfoRes.getCity());
        wechatUser.setCountry(userInfoRes.getCountry());
        wechatUser.setProvince(userInfoRes.getProvince());
        wechatUser.setLanguage(userInfoRes.getLanguage());
        wechatUser.setHeadimgurl(userInfoRes.getHeadimgurl());
        wechatUser.setSubscribe_time(userInfoRes.getSubscribe_time());
        wechatUser.setRemark(userInfoRes.getRemark());
        return wechatUser;
    }
    public WechatUser getWechatUser(String appid,String openId)  throws  Exception{
        Criteria criteria = new Criteria();
        criteria.add(Restrictions.eq("appId", appid));
        criteria.add(Restrictions.eq("openid", openId));
        criteria.addOrder(com.jade.framework.base.criterion.Order.desc("createTime"));
        PagingList<WechatUser> list = wechatUserDao.queryEntity(WechatUser.class, criteria);
        if(list!=null && list.size()>0) return list.get(0);
        return null;
    }
    public WechatUser getWechatUser(String openId)  throws  Exception{
        Criteria criteria = new Criteria();
        criteria.add(Restrictions.eq("openid", openId));
        criteria.addOrder(com.jade.framework.base.criterion.Order.desc("createTime"));
        PagingList<WechatUser> list = wechatUserDao.queryEntity(WechatUser.class, criteria);
        if(list!=null && list.size()>0) return list.get(0);
        return null;
    }
    /**
     * 同步微信用户
     * @param customer
     * @param appid
     * @throws Exception
     */
    @Transactional(propagation= Propagation.REQUIRED)
    public List<WechatUser>  synchronizeWxUser(Customer customer,String appid)  throws  Exception{
        List<WechatUser> newCrmUser=new ArrayList<WechatUser>();
        List<UserBatchGetReqTool> allOpendIds=new ArrayList<UserBatchGetReqTool>();
        UserGetBusiness business=new UserGetBusiness(appid);
        UserGetReq req=new UserGetReq();
        UserGetRes res=business.run(req);
        if(res.getCount()>0 && res.getData()!=null && res.getData().getOpenid()!=null  && res.getData().getOpenid().length>0){
             for(String openid : res.getData().getOpenid()){
                 UserBatchGetReqTool newuser=new UserBatchGetReqTool();
                 newuser.setOpenid(openid);
                 allOpendIds.add(newuser);
             }
            if(StringUtils.isNotEmpty(res.getNext_openid())){
                List<UserBatchGetReqTool> nextOpendids=this.synchronizeWxUser(appid,res.getNext_openid());
                allOpendIds.addAll(nextOpendids);
            }
        }
        if(allOpendIds!=null && allOpendIds.size()>0){
            newCrmUser=this.getAllWechatUser(allOpendIds,customer,appid);
            wechatUserDao.batchSave(newCrmUser);
        }
        return newCrmUser;
    }
    /**
     * 循环迭代获取用户
     * @param appid
     * @param nextOpenId
     * @return
     * @throws Exception
     */
    public List<UserBatchGetReqTool> synchronizeWxUser(String appid,String nextOpenId)  throws  Exception{
        List<UserBatchGetReqTool> allOpendIds=new ArrayList<UserBatchGetReqTool>();
        UserGetBusiness business=new UserGetBusiness(appid);
        UserGetReq req=new UserGetReq();
        req.setNext_openid(nextOpenId);
        UserGetRes res=business.run(req);
        if(res.getCount()>0 && res.getData()!=null && res.getData().getOpenid()!=null  && res.getData().getOpenid().length>0){
            for(String openid : res.getData().getOpenid()){
                WechatUser wechatUser=this.getWxUser(appid,openid);
                if(wechatUser!=null && wechatUser.getId()>0)continue;
                UserBatchGetReqTool newuser=new UserBatchGetReqTool();
                newuser.setOpenid(openid);
                allOpendIds.add(newuser);
            }
            if(StringUtils.isNotEmpty(res.getNext_openid())){
                List<UserBatchGetReqTool> nextOpendids=this.synchronizeWxUser(appid,res.getNext_openid());
                allOpendIds.addAll(nextOpendids);
            }
        }
        return allOpendIds;
    }

    private List<WechatUser> getAllWechatUser(List<UserBatchGetReqTool> list,Customer customer,String appid) throws Exception{
        List<WechatUser> wechatUsers=new ArrayList<WechatUser>();
        if(list.size()<=0) return wechatUsers;
        UserInfoBatchetBusiness _business=new UserInfoBatchetBusiness(appid);
        int pageCount=list.size()/100;//分页大小
        for(int i=1;i<=pageCount;i++){
            List<UserBatchGetReqTool> reslist=list.subList((i-1)*100,i*100);
            UserInfoBatchGetRes res=_business.run(reslist);
            if(res==null || res.getUser_info_list()==null || res.getUser_info_list().size()<=0)continue;
            for(UserInfoRes userInfoRes : res.getUser_info_list()){
                WechatUser wechatUser=new WechatUser();
                wechatUser.setAppId(appid);
                wechatUser.setSubscribe(userInfoRes.getSubscribe());
                wechatUser.setOpenid(userInfoRes.getOpenid());
                wechatUser.setNickname(escapeExprSpecialWord(userInfoRes.getNickname()));
                wechatUser.setSex(userInfoRes.getSex());
                wechatUser.setCity(userInfoRes.getCity());
                wechatUser.setCountry(userInfoRes.getCountry());
                wechatUser.setProvince(userInfoRes.getProvince());
                wechatUser.setLanguage(userInfoRes.getLanguage());
                wechatUser.setHeadimgurl(userInfoRes.getHeadimgurl());
                wechatUser.setSubscribe_time(userInfoRes.getSubscribe_time());
                wechatUser.setRemark(userInfoRes.getRemark());
                wechatUser.setOwnerId(customer.getOwnerId());
                wechatUser.setCreatorId(customer.getId());
                wechatUser.setCreator(customer.getName());
                wechatUsers.add(wechatUser);
            }
        }
        if(list.size()/100>0){
            List<UserBatchGetReqTool> endlist=list.subList((pageCount-1)*100,(pageCount-1)*100+list.size()%100);
            UserInfoBatchGetRes res=_business.run(endlist);
            if(res!=null && res.getUser_info_list()!=null){
                for(UserInfoRes userInfoRes : res.getUser_info_list()){
                    WechatUser wechatUser=new WechatUser();
                    wechatUser.setAppId(appid);
                    wechatUser.setSubscribe(userInfoRes.getSubscribe());
                    wechatUser.setOpenid(userInfoRes.getOpenid());
                    wechatUser.setNickname(userInfoRes.getNickname());
                    wechatUser.setSex(userInfoRes.getSex());
                    wechatUser.setCity(userInfoRes.getCity());
                    wechatUser.setCountry(userInfoRes.getCountry());
                    wechatUser.setProvince(userInfoRes.getProvince());
                    wechatUser.setLanguage(userInfoRes.getLanguage());
                    wechatUser.setHeadimgurl(userInfoRes.getHeadimgurl());
                    wechatUser.setSubscribe_time(userInfoRes.getSubscribe_time());
                    wechatUser.setRemark(userInfoRes.getRemark());
                    wechatUser.setOwnerId(customer.getOwnerId());
                    wechatUser.setCreatorId(customer.getId());
                    wechatUser.setCreator(customer.getName());
                    wechatUsers.add(wechatUser);
                }
            }
        }
        return wechatUsers;
    }
    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (StringUtils.isNotBlank(keyword)) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword.replaceAll("[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]", "*");
    }
}
